#coding:utf-8

# --------------------------------------------------------------------------------
# 上岗持证要求的管理
# --------------------------------------------------------------------------------
module PaperRegisterService
  def self.registered(app)

    app.get "/?" do
      PaperRegisterDomain.all.to_json
    end
    
    app.get "/:id" do
      param :id, Integer, required: true
      
      elem =  PaperRegisterRepo[params[:id]]
      elem.nil? ? raise("not found paper register: #{params[:id]}") : elem.perfect.to_json
    end

    app.post "/?" do
      param :employee_id,    String,   required: true
      param :paper_type_id,  Integer,  required: true
      param :paper_no,       String,   required: true
      param :due_date,       Date,     required: true
      param :descr,          String,   required: false
      param :state,          String,   required: false, in: %w(normal expired failure)

      PaperRegisterDomain.create(params.symbolize_keys).to_json
    end

    app.put "/:id/?" do
      param :id,   Integer, required: true
      param :paper_no,       String,   required: false
      param :due_date,       Date,     required: false
      param :descr,          String,   required: false
      param :state,          String,   required: false, in: %w(normal expired failure)

      
      elem = PaperRegisterRepo[params[:id]]
      valid_params = params.keep_if{|k,v| %w(paper_no due_date descr state).include?(k)}.symbolize_keys
      if elem
        new_elem = elem.update(valid_params)
        (new_elem ? (new_elem.check_expire; new_elem.save) : elem).perfect.to_json
      else
        {result: :error, message: "update paper register failed, not found id: #{params[:id]}"}.to_json        
      end
    end

    app.delete "/:id/?" do
      param :id, Integer, required: true
      
      elem = PaperRegisterRepo[params[:id]]
      if elem
        begin
          elem.delete
          {result: :ok, id: elem.id}.to_json
        rescue SQLite3::ConstraintException
          {result: :error, message: "delete paper register failed, id: #{elem.id}"}.to_json
        end
      else
        {result: :error, message: "delete paper register failed, not found id: #{params[:id]}"}.to_json
      end
    end
  end
end
